package com.aaronprj.school.mbooks.resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.aaronprj.common.entities.SgmenuEntityManager;
import com.aaronprj.common.entities.mbooks.Message;
import com.aaronprj.common.entities.mbooks.User;
import com.aaronprj.common.enums.UserRole;
import com.aaronprj.common.utils.CommonEntityManager;
import com.aaronprj.common.utils.EnumHelper;
import com.aaronprj.common.utils.mbooks.SystemInitialHelper;
import com.aaronprj.common.web.uivo.BaseEntity;
import com.aaronprj.school.mbooks.uivo.UIMessage;
import com.aaronprj.school.mbooks.uivo.UIUser;



@Path("/user")
public class UserResource extends MbooksResource{

    // The Java method will process HTTP GET requests

    @Path("/{id}")
    @GET 
	@Produces(MediaType.APPLICATION_JSON)
    public String getUserInfor(@PathParam("id") int userid) {
    	
    	
    	User user =  (User) CommonEntityManager.find(User.class, userid);

    	if(null == user){
    		SystemInitialHelper.initial();
    		
    		user =  (User) CommonEntityManager.find(User.class, userid);
    	}
    	
    	if(null == user){
            return this.writeValueAsString(generateResult(UIUser.class, false, "No record found", ""));
    	}
    	
    	UIUser uiuser = generateResult(UIUser.class, true, "", "");
    	uiuser.setId(user.getId());
    	uiuser.setUserName(user.getUserName());
    	uiuser.setFirstName(user.getFirstName());
    	uiuser.setPassword(user.getPassword());
    	uiuser.setPhoneNumber(user.getPhoneNumber());
    	uiuser.setEmail(user.getEmail());
    	uiuser.setRole(user.getRole().getValue());
    	uiuser.setRoleName(user.getRole().getDisplayName());
    	uiuser.setCourse(user.getCourse());
    	uiuser.setAddress(user.getAddress());
    	uiuser.setPostCode(user.getPostCode());


    	return this.writeValueAsString(uiuser);
    }
    

    @SuppressWarnings("unchecked")
	@Path("/users")
    @GET 
	@Produces(MediaType.APPLICATION_JSON)
    public String getUserInfor() {
    	
    	
    	List<User> users =  (List<User>) SgmenuEntityManager.getAllEntities("User");

    	if(null == users || users.isEmpty()){
            return this.writeValueAsString(generateResult(UIUser.class, false, "No record found", ""));
    	}
    	List<UIUser> us = new ArrayList<UIUser>();
    	for(User u:users){
        	UIUser uiuser = new UIUser();
        	uiuser.setId(u.getId());
        	uiuser.setUserName(u.getUserName());
        	uiuser.setFirstName(u.getFirstName());
        	uiuser.setPhoneNumber(u.getPhoneNumber());
        	uiuser.setEmail(u.getEmail());
        	uiuser.setRole(u.getRole().getValue());
        	uiuser.setRoleName(u.getRole().getDisplayName());
        	uiuser.setCourse(u.getCourse());
	    	uiuser.setAddress(u.getAddress());
	    	uiuser.setPostCode(u.getPostCode());
	    	
        	us.add(uiuser);
    	}

    	return this.writeValueAsString(us);
    }
    
    @Path("/login/{username}/{password}")
    @POST 
	@Produces(MediaType.APPLICATION_JSON)
    public String login(@PathParam("username") String username, @PathParam("password") String password){
    	
    	UIUser uiuser = generateResult(UIUser.class, true, "", "");
    	try {
			User user =  (User) SgmenuEntityManager.getEntity("User.findByName","userName", username);
			
			if(null == user){
				//if first time login,,have to initial the user data
				SystemInitialHelper.createUsers();
				
				user =  (User) SgmenuEntityManager.getEntity("User.findByName","userName", username);
			}
			
			if(null == user){
				uiuser.setMsgCode("Login name not matched!");
				uiuser.setMsgDiscription("Please input your correct login name!");
				uiuser.setSuccess(false);
				
			}else if(!password.equals(user.getPassword())){
				uiuser.setMsgCode("Login password not matched!");
				uiuser.setMsgDiscription("Please input your correct password!");
				uiuser.setSuccess(false);
			}else{
				uiuser.setId(user.getId());
				uiuser.setEmail(user.getEmail());
				uiuser.setUserName(user.getUserName());
				uiuser.setFirstName(user.getFirstName());
		    	uiuser.setRole(user.getRole().getValue());
		    	uiuser.setRoleName(user.getRole().getDisplayName());
				uiuser.setSessionId(getSessionId().toString());
		    	uiuser.setCourse(user.getCourse());
		    	uiuser.setAddress(user.getAddress());
		    	uiuser.setPostCode(user.getPostCode());
		    	
		    	int unreadCount = 0;
				List<Message> msgs = (List<Message>) SgmenuEntityManager.getItem("Message.findByRecieverId", "recieverId", user.getId());
		    	if(null != msgs && !msgs.isEmpty()){
		    		for(Message m:msgs){
		    			
		    			uiuser.addUIMessage(new UIMessage(m.getId(),m.getSenderId(), m.getSenderName(),m.getRecieverId(),m.getContent(),m.isUnreaded(),m.getCreateDate()));
		    			if(m.isUnreaded()){
		    				unreadCount ++;
		    			}
		    		}
		    	}

		    	uiuser.setUnreadCount(unreadCount);

				
				loginedusers.put(uiuser.getSessionId(), uiuser);
			}
		} catch (Exception e) {
			uiuser.setMsgCode("Login unsuccessfull!");
			uiuser.setMsgDiscription("Please input your correct login name and password try again!");
			uiuser.setSuccess(false);
			
			e.printStackTrace();
		}
    	
    	return this.writeValueAsString(uiuser);
    }
    
    
    @POST
	@Produces(MediaType.APPLICATION_JSON)
    public String saveUser(@QueryParam("id") int id, 
			 @QueryParam("userName") String userName,
			 @QueryParam("firstName") String firstName, 
			 @QueryParam("password") String password, 
			 @QueryParam("email") String email, 
			 @QueryParam("role") int role, 
			 @QueryParam("address") String address, 
			 @QueryParam("postCode") String postCode, 
			 @QueryParam("course") String course, 
			 @QueryParam("phoneNumber") String phoneNumber) {
    	BaseEntity be;
    	try {
			User user;
			if(id == 0){
				user = new User();
				be = generateResult(BaseEntity.class, true, "Your register successfull!", "Thanks for your registion.");
			}else{
				user =  (User) CommonEntityManager.find(User.class, id);
				be = generateResult(BaseEntity.class, true, "Your information update successfull!", "");
			}

			UserRole userRole = EnumHelper.getEnumValue(UserRole.class, role);
			
			user.setUserName(userName);
			user.setFirstName(firstName);
			if(null != password && !"".equals(password)){
				user.setPassword(password);
			}
			user.setEmail(email);
			user.setRole(userRole);
			user.setPhoneNumber(phoneNumber);
			user.setCourse(course);
			user.setAddress(address);
			user.setPostCode(postCode);
			
			SgmenuEntityManager.save(user, id==0);
			
		} catch (Exception e) {
			be = generateResult(BaseEntity.class, false, "Your register unsuccessfull!", "Please validate your information and try again.");
			e.printStackTrace();
		}
    	
    	return this.writeValueAsString(be);
    }
    

    @Path("/msg")
    @POST 
	@Produces(MediaType.APPLICATION_JSON)
    public String sendMessage(@QueryParam("senderId") int senderId, 
			 @QueryParam("senderName") String senderName,
			 @QueryParam("recieverId") int recieverId, 
			 @QueryParam("content") String content){

    	BaseEntity be;
    	
    	Message msg = new Message();
    	msg.setSenderId(senderId);
    	msg.setSenderName(senderName);
    	msg.setRecieverId(recieverId);
    	msg.setContent(content);
    	
    	msg.setUnreaded(true);
    	msg.setCreateDate(new Date());
    	
    	SgmenuEntityManager.save(msg, true);

		be = generateResult(BaseEntity.class, true, "Your register successfull!", "Thanks for your registion.");
    	return this.writeValueAsString(be);
    }
    
    @Path("/msg/{id}")
    @GET
	@Produces(MediaType.APPLICATION_JSON)
    public String sendMessage(@PathParam("id") int id){
    	BaseEntity be;
    	
    	SgmenuEntityManager.deleteItem(Message.class, id);

		be = generateResult(BaseEntity.class, true, "Your register successfull!", "Thanks for your registion.");

    	return this.writeValueAsString(be);
    }
	
}
